package chen.web.config.spring;

import java.util.Observable;
import java.util.Observer;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import chen.web.config.ConfigRepository;
import chen.web.config.EmailConfig;
import chen.web.email.DirectSender;
import chen.web.email.EmailAddress;
import chen.web.email.EmailSender;
import chen.web.email.SMTPSender;
import chen.web.email.SimpleEmail;

@Configuration
public class SystemEmailSenderConfig {

	public @Bean EmailSender emailSender(){
		EmailSender sender = new MyEmailSender();
		ConfigRepository.instance().addObserver((Observer)sender);
		return sender;
	}
	
	private static class MyEmailSender implements EmailSender, java.util.Observer{
		private EmailSender sender = null;
		
		private  MyEmailSender(){
			EmailConfig config = ConfigRepository.instance().get(EmailConfig.class);
			init(config);
		}
		
		private void init(EmailConfig config){
			if(config.isUseSMTP()){
				sender = new SMTPSender(new EmailAddress(config.getSenderEmail()), config.getSmtpHost(), config.getUsername(), config.getPassword());
			} else {
				sender = new DirectSender(new EmailAddress(config.getSenderEmail()));
			}
		}
		
		@Override
		public void update(Observable o, Object arg) {
			// TODO Auto-generated method stub
			if(arg instanceof EmailConfig){
				init((EmailConfig)arg);
			}
		}

		@Override
		public boolean send(SimpleEmail email) {
			// TODO Auto-generated method stub
			return sender.send(email);
		}
		
	}
}
